<template>
  <input 
    v-if="!isNativeMaxlength"
    :type="type" 
    :value="currentValue" 
    :placeholder="placeholder" 
    :disabled="disabled" 
    :readonly="readonly" 
    :autofocus="autofocus"  
    :name="name" 
    @click="handleClick" 
    @input="handleInput" 
    @focus="handleFocus" 
    @blur="handleBlur"/>
  <input 
    v-else
    :type="type" 
    :maxlength="maxlength"
    :value="currentValue" 
    :placeholder="placeholder" 
    :disabled="disabled" 
    :readonly="readonly" 
    :autofocus="autofocus"  
    :name="name" 
    @click="handleClick" 
    @input="handleInput" 
    @focus="handleFocus" 
    @blur="handleBlur"/>
</template>
<script>
import Utils from '../../utils';
export default {
  name: 'z-input',
  props: {
    type: {
      type: String,
      default: 'text'
    },
    placeholder: String,
    maxlength: {
      type:[Number,String],
      default:1000
    },
    value: {
      type: [String,Number],
      default: ''
    },
    name: String,
    disabled: {
      type: Boolean,
      default: false
    },
    readonly: Boolean,
    autofocus: Boolean,
    checkType: String,
    isNativeMaxlength:{
      type: Boolean,
      default: false
    }
  },

  data() {
    return {
      currentValue: this.value,
      maxlenValue: this.value
    }
  },
  methods: {
    handleClick(e) {
      this.$emit('click',e)
    },
    handleInput(e) {
      this.currentValue = e.target.value
      if(!this.isNativeMaxlength){
        this.__maxLength()
      }
      this.$emit('input',this.currentValue)
      if (this.checkType) {
        switch (this.checkType) {
          // 是否是数字
          case 'number':
            this.__isNumber()
            return
          default:
            break;
        }
      }
    },
    handleFocus(e) {
      this.$emit('focus', e)
    },
    handleBlur(e) {
      this.$emit('blur', e)
    },

    // 字符长度限制
    __maxLength() {
      let len = Utils.format.checkCh(this.currentValue)
      if (len > Math.ceil(parseInt(this.maxlength / 2))) {
        this.currentValue = this.maxlenValue 
      } else {
        this.maxlenValue = this.currentValue
      }
      this.$emit('input',this.currentValue)
    },

    // 是否是数字
    __isNumber(){
      this.currentValue = this.currentValue.replace(/[^\d]/g,'')
      this.$emit('input',this.currentValue)
    }
  }
}
</script>

